package com.fan.cachewebview.core.interceptor

import android.content.Context
import android.text.TextUtils
import com.fan.cachewebview.bean.WebResource
import com.fan.cachewebview.core.CacheConfig
import com.fan.cachewebview.core.filter.MimeTypeFilterApi
import com.fan.cachewebview.net.OkHttpResourceLoader
import com.fan.cachewebview.net.ResourceLoadApi
import com.fan.cachewebview.net.SourceRequest
import javax.security.auth.Destroyable

/**
 * @description 类型过滤
 * @date: 2022/3/1 11:01
 * @author: fan
 */
class FilterInterceptor : ResourceInterceptor, Destroyable {
    private var mResourceLoader: ResourceLoadApi? = null
    private var mMimeTypeFilter: MimeTypeFilterApi? = null

    constructor(context: Context, cacheConfig: CacheConfig) {
        mResourceLoader = OkHttpResourceLoader(context)
        mMimeTypeFilter = cacheConfig.getFilter()
    }

    override fun load(chain: Chain): WebResource? {
        var request = chain.getRequest()
        var mime = request?.mime

        var isFilter = if (TextUtils.isEmpty(mime)) {
            false
        } else {
            mMimeTypeFilter!!.isFilter(mime!!)
        }

        val sourceRequest = SourceRequest(request!!, isFilter)
        val resource = mResourceLoader!!.getResource(sourceRequest)
        return resource ?: chain.process(request)
    }

}